package cn.jn.lhm.part01;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import static cn.jn.lhm.part01.ByteBufferUtil.debugAll;

/**
 * @author lhm 2753914576@qq.com
 * @time 2022/7/3 - 16:41
 **/
public class ByteBufferExam {
    public static void main(String[] args) {
        // 粘包和半包
        ByteBuffer buffer = ByteBuffer.allocate(32);
        buffer.put("hello, word\nI'm zhangSan\nHo".getBytes());
        split(buffer);
        buffer.put("w are you?\n".getBytes());
        split(buffer);
    }

    private static void split(ByteBuffer buffer) {
        buffer.flip();

        for (int i = 0; i < buffer.limit(); i++) {
            // get(i) 读取不改变 position 的位置
            if (buffer.get(i) == '\n') {
                int length = i + 1 - buffer.position();
                // 将这条消息存储到新的ByteBuffer中保存起来
                ByteBuffer target = ByteBuffer.allocate(length);

                // 移动position的位置
                for (int j = 0; j < length; j++) {
                    target.put(buffer.get());
                }
                debugAll(target);
                // target.flip();
                // System.out.println(StandardCharsets.UTF_8.decode(target));
            }
        }

        // 将未读取完成的数据放在下一条数据中进行读取
        buffer.compact();
    }
}
